<?php

namespace app\data\command;

use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;

/**
 * 修改返利状态
 * Class CalculateInterest
 * @package app\data\command
 */
class UpdateReturnRate extends Command
{
    protected function configure()
    {
        $this->setName('xdata:UpdateReturnRate');
        $this->setDescription('定时更新利息');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        try {
            $start = date('Y-m-01');
            $map = [];
            $map[] = ['deleted_status', '=', 0];
            $map[] = ['status', '=', 1];
            $map[] = ['end_at', '>', $start];
            $map[] = ['goods_return_rule', '=', 1];

            $count = 0;
            $this->app->log->info('开始更改返息状态');
            $this->app->db->name('ShopOrder')->where($map)->chunk(50, function ($orders) use($count){
                foreach ($orders as $order){
                    if($this->calculate($order)){
                        $count ++;
                    }
                }
            });
            $this->app->log->info('更改完成返息状态，共'.$count.'条成功');

        } catch (Exception $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->setQueueError($exception->getMessage());
        }
    }


    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    private function calculate($order): bool
    {
        $month = getLastMonth(date('Y-m'));
        $orderLog = $this->app->db->name('ShopOrderReturnRateLog')->where('order_id' , $order['id'])->where('month' , $month)->find();
        if($orderLog){
            $this->app->db->name('ShopOrder')
                ->where('id',$order['id'])
                ->update(
                    [
                        'update_at'=>date('Y-m-d H:i:s'),
                        'current_lxje'=> $order['current_lxje']+$orderLog['money'],
                    ]
                );
            $this->app->db->name('ShopOrderReturnRateLog')
                ->where('id',$orderLog['id'])
                ->update(
                    [
                        'update_at'=>date('Y-m-d H:i:s'),
                        'status'=> 1,
                    ]
                );
            $this->app->log->info("订单id{$order['id']}更改完成");
            return true;
        }
        $this->app->log->info("订单id{$order['id']}更改失败");
        return false;
    }
}